package top.szhome.develop.controller;

import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.szhome.develop.generator.FileNode;
import top.szhome.develop.service.GeneratorService;
import top.szhome.develop.service.ModelService;
import top.szhome.develop.vo.GenerateVO;
import top.szhome.framework.core.tools.exception.SzhomeException;
import top.szhome.framework.core.tools.support.Resp;
import top.szhome.framework.core.tools.util.WebUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 代码生成器
 *
 * @author 唐加利
 * @date 2023/8/30
 **/
@RequiredArgsConstructor
@RestController
@RequestMapping("/develop/generator")
public class GeneratorController {

    private final GeneratorService generatorService;

    /**
     * 预览模型代码生成结果
     * @param modelIds
     * @return
     */
    @Operation(summary = "预览模型代码生成结果")
    @GetMapping("preview/{modelIds}")
    public Resp<List<FileNode>> preview(@PathVariable List<Long> modelIds){
        return Resp.success(generatorService.preview(modelIds));
    }

    /**
     * 生成代码，并下载zip包
     * @param modelIds
     * @return
     */
    @GetMapping("model/{modelIds}")
    public void generateModelCode(@PathVariable List<Long> modelIds, HttpServletResponse response){
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + modelIds.get(0) + ".zip");
            generatorService.generate(modelIds, response.getOutputStream());
        } catch (IOException e) {
            throw new SzhomeException("获取响应流失败" , e);
        }
    }

    /**
     * 获取模型常用脚本
     *
     * @param modelId
     * @param templateSchemaCode
     * @param templateCode
     * @return
     */
    @GetMapping("script")
    public Resp<String> generateModelScript(Long modelId, String templateSchemaCode, String templateCode){
        return Resp.success(generatorService.generate(modelId, templateSchemaCode, templateCode));
    }

    /**
     * 根据生成工程所属全部模型的代码
     * @param datasourceId
     * @return
     */
    @GetMapping("datasource")
    public Resp<String> generateDatasourceCode(Long datasourceId){
        return Resp.success(null);
    }

    /**
     * 根据生成工程所属全部模型的代码
     * @param projectId
     * @return
     */
    @GetMapping("project")
    public Resp<String> generateProjectCode(Long projectId){
        return Resp.success(null);
    }

}
